var fs = require("fs");
const db = require("../db/index");
// 引入七牛模块
var qiniu = require("qiniu");
//要上传的空间名
var bucket = "kukiblog";
var imageUrl = "img.kukikuk.icu"; // 域名名称
var accessKey = "dXu5nJdraS7TZI3Uc4LXIH19edGtfuUWAQTO_0xH";
var secretKey = "sV4iULn8bCTPzHo7WoztzvPuUPWn0gsTvda_Gh5D";
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

var options = {
  scope: bucket,
  expires:7200
};
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken = putPolicy.uploadToken(mac);

var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1;

// 获取文件链接
exports.getAnnex = (req, res) => {
  const sql = "select * from annexlist where id = ?";
  db.query(sql, req.params.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
      return res.send({
        code:200,
        message:'获取附件链接成功',
        url:result[0].url
      })
  });
};

//上传文件
exports.uploadFile = (req, res) => {
  var base64Data = req.body.file.replace(/^data:(.*?);base64,/, "");
  var dataBuffer = Buffer.from(base64Data, "base64");
  var fileName = Date.now() + "." + req.body.type;
  let path = "./public/file/" + fileName;
  fs.writeFile(path, dataBuffer, function (err) {
    if (err) {
      console.log(err);
      res.end(
        JSON.stringify({
          status: "102",
          msg: err,
        })
      );
    } else {
      var localFile = path;
      var formUploader = new qiniu.form_up.FormUploader(config);
      var putExtra = new qiniu.form_up.PutExtra();
      var key = fileName;

      // 文件上传
      formUploader.putFile(
        uploadToken,
        key,
        localFile,
        putExtra,
        function (respErr, respBody, respInfo) {
          if (respErr) {
            res.send(
              JSON.stringify({
                status: "-1",
                msg: "上传失败,请稍后重试",
                error: respErr,
              })
            );
            uploadToken = putPolicy.uploadToken(mac);
          }
          if (respInfo.statusCode == 200) {
            var src = "http://" + imageUrl + `/` + respBody.key;
            let annex = {
              type: req.body.type,
              name: req.body.name,
              url: src,
              uploaderid: req.user?.id,
            };
            const sql = "insert into annexlist set ?";
            db.query(sql, annex, (err, result) => {
              if (err)
                return res.send({
                  code: 500,
                  message: "数据库异常" + err.message,
                });
              res.send({
                code: 200,
                message: "上传成功",
                data: {
                  id: result.insertId,
                  type:req.body.type
                },
              });
            });
          } else {
            res.send(
              JSON.stringify({
                status: "-1",
                msg: "上传失败",
                error: JSON.stringify(respBody),
              })
            );
          }
          // 上传之后删除本地文件
          fs.unlinkSync(path);
          return;
        }
      );
    }
  });
};
